package toy.keli.edic.ui.listenbook

import VerticalTimeline
import android.graphics.Bitmap
import android.speech.tts.TextToSpeech
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.Card
import androidx.compose.material.Divider
import androidx.compose.material.LinearProgressIndicator
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.google.mlkit.vision.common.InputImage
import toy.keli.edic.R
import toy.keli.edic.data.Db
import toy.keli.edic.data.DictionaryDatabase
import toy.keli.edic.data.GlobalVal
import toy.keli.edic.data.PreviewData
import toy.keli.edic.data.config.BookConf
import toy.keli.edic.data.local.entity.ArticleEntity
import toy.keli.edic.data.model.Article
import toy.keli.edic.data.model.Book
import toy.keli.edic.data.parse.Image2Text
import toy.keli.edic.ui.history.HistoryWords
import toy.keli.edic.ui.home.HomeEvents
import toy.keli.edic.ui.home.homescreen.BookNavInfo
import toy.keli.edic.ui.home.homescreen.DefaultPageWordDetail
import toy.keli.edic.ui.home.homescreen.DefaultPageWordTitle
import toy.keli.edic.ui.home.homescreen.HistoryWordsShow
import toy.keli.edic.ui.home.homescreen.SearchComponent
import toy.keli.edic.ui.listenbook.BookTools.Companion.ListenPage
import toy.keli.edic.ui.listenbook.BookTools.Companion.LoadBookPage
import toy.keli.edic.ui.listenbook.BookTools.Companion.ReadPage
import toy.keli.edic.ui.listenbook.BookTools.Companion.SourcePage
import toy.keli.edic.ui.listenbook.BookTools.Companion.StatPage
import toy.keli.edic.ui.listenbook.BookTools.Companion.topTools
import toy.keli.edic.ui.listenbook.ListenBookData.viewModes
import toy.keli.edic.ui.main.components.CloseButton
import toy.keli.edic.ui.main.components.Display.mt
import toy.keli.edic.ui.main.components.InfoDialog
import toy.keli.edic.ui.main.components.RbButton
import toy.keli.edic.ui.main.components.SingleRowColorPicker
import toy.keli.edic.ui.main.extend.MText
import toy.keli.edic.ui.main.extend.MainRun
import toy.keli.edic.ui.main.extend.annotatedText
import toy.keli.edic.ui.main.extend.bgRun
import toy.keli.edic.ui.main.extend.scrollEnabled
import toy.keli.edic.ui.main.extend.stringRun
import toy.keli.edic.ui.navigation.NavScreen
import toy.keli.edic.util.ActivityRun
import toy.keli.edic.util.MediaUtil
import toy.keli.edic.view.MPopMenu
import toy.keli.edic.view.RichText
import toy.keli.edic.view.RichTextFont
import toy.keli.edic.view.RichTextFonts
import java.util.UUID

/**
 * 书本单词列表 带统计信息
 * 模拟多看的听书功能
 */
@Composable
@Preview
fun ListenBookScreen(words: List<String> = listOf("")) {
    if( LocalInspectionMode.current) {
        ActivityRun.context = LocalContext.current
    }
    val lbd =  remember {  ListenBookData() }
    if( LocalInspectionMode.current) {
        PreviewData.listenBookScreen(lbd)
//        HomeEvents.downMenuOpen = true
        lbd.vMode = viewModes.read
    }else{
        lbd.initializeTTS()
    }
    val args = words
    lbd.apply {

        LaunchedEffect(textToRead) {
            if (textToRead.size > 0) {
                size=textToRead.size
                bgRun {
                    initData(textToRead)
                }
            }
        }
        LaunchedEffect(dIndex,searchScrollOffset) {
            if (scrollState != null) {
//                scrollState!!.animateScrollToItem(dIndex)
                scrollState!!.scrollToItem(dIndex,searchScrollOffset)

            }
        }
        remember (scrollIndex){
            BookConf.instance.apply {
                //上次开启的位置
                if (scrollIndex == 0) {
                    scrollIndex = lastScrollIndex()
                }
                //保存最新位置
                lastScrollIndex(scrollIndex)
            }
            showPos
        }
        if (args.size == 1) {
            if (sampleFileUrl != args[0]) {
                sampleFileUrl = args[0]
                loadTextFromUrl(sampleFileUrl)
            }
        } else if (args.size == 0) {

        } else {
            textToRead = args.map { it }
        }
        if(bColor == Color.Unspecified) {
            bColor = MaterialTheme.colorScheme.background
        }
        Box (modifier = Modifier.background(bColor)){
                Column(
//                verticalArrangement = Arrangement.spacedBy(10.dp),
                    modifier = Modifier
                        .fillMaxSize() // Remove padding
                        .padding(5.dp)
                ) {
                    Row(modifier = Modifier.padding(10.dp, 15.dp,40.dp,5.dp)) {
                        var isTextTruncated by remember { mutableStateOf(false) }
                        val menu = MPopMenu(listOf(MPopMenu.dataClass(title)))
                        if(title.isEmpty()) title = Book.name()
                        Text(
                            title,
                            style = MaterialTheme.typography.headlineMedium,
                            color = MaterialTheme.colorScheme.onBackground,
                            maxLines = 1, // 限制只显示一行（不换行）
                            overflow = TextOverflow.Ellipsis // 超出部分显示...
                            ,onTextLayout = { layoutResult ->
                                // 文本被截断时才允许点击弹出
                                isTextTruncated = layoutResult.hasVisualOverflow
                            }
                            , modifier = Modifier.clickable {
                                if(isTextTruncated) menu.show()
                            }
                        )
                        menu.add()
//                    Spacer(Modifier.weight(1f))
//                    ScanButton({
//                            loadTextFromScan()
//                    })
                    }

                    when (vMode) {
                        viewModes.source -> SourcePage()
                        viewModes.stat -> {
                            if (sortedList.value.size == 0 && textToRead.size > 0) bgRun {
                                initData(textToRead)
                            }
                            StatPage()
                        }

                        viewModes.listen -> {
                            if (sentencesQueue.size == 0 && textToRead.size > 0) bgRun {
                                initData(
                                    textToRead
                                )
                            }
                            ListenPage()
                        }

                        else -> {
                            if (args.isEmpty()) {
                                LoadBookPage();
                            } else {
                                ReadPage()
                            }
                        }
                    }
                }
            if(HomeEvents.downMenuOpen) {
                topTools()
            }
            if(showPos && size>0){
                val p =  "$scrollIndex/$size"
//                val p =  String.format("%.2f%", scrollIndex*100f/size)
                //val p =  scrollState!!.calculateScrollPercentage()

                RbButton(
                    text = "$p"
                ) {
                    InfoDialog.show {
                        Card {
                            Column(modifier = Modifier.padding(5.dp)) {
//                                Row{ Spacer(Modifier.weight(1f)) ; CloseButton {InfoDialog.close()  } }
                                VerticalTimeline(startYear = 1, endYear = textToRead.size,currentYear = scrollIndex,events=chaptersEvent){
                                    dIndex = it
                                    InfoDialog.close()
                                }
                            }
                        }
                    }
                }
            }

            if(hasSugWord){
                val wordState by GlobalVal.wordViewModel.wordState.collectAsState()
                if(wordState.wordModel !=null) {
                    HistoryWords.add(wordState.wordModel)
                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .pointerInput(Unit){}
                            .background(MaterialTheme.colorScheme.background)
                    ) {
                        Spacer(Modifier.height(50.dp))
                        DefaultPageWordTitle(GlobalVal.wordViewModel)
                        SearchComponent(wordState, GlobalVal.wordViewModel)
                    }
                }else{
                    Column ( modifier = Modifier
                        .fillMaxSize()
                        .clickable {
                            hasSugWord=false
                            GlobalVal.isSearchVisible.value = false
                        }
                        .background(MaterialTheme.colorScheme.background),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Center
                    ){
                        HistoryWordsShow()
                    }
                }
            }

        }

    }
}

class BookTools {
    companion object {
        //顶部菜单
        @Composable
        fun ListenBookData.topTools(){
            Column (modifier = Modifier
                .alpha(0.9f)
                .background(MaterialTheme.colorScheme.background)
                .fillMaxWidth()
                .padding(10.dp, 10.dp, 0.dp, bottom = 0.dp)
                .pointerInput(Unit) {
                    HomeEvents.timeOutClosedDownMenu = false;
                }
            ){
                BookNavInfo(canArticleChange=true)
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Text(mt("视图")+":")
                    RadioLableButton("看书", vMode == viewModes.read) {
                        vMode = viewModes.read
                    }
                    RadioLableButton("听书", vMode == viewModes.listen) {
                        vMode = viewModes.listen
                    }

                    if (sourceImg != null) {
                        RadioLableButton("原文件", vMode == viewModes.source, onClick = {
                            vMode = viewModes.source
                        })
                    }
                }
                SingleRowColorPicker(bColor,title=mt("背景")+":" ){
                    bColor = it
                }
                Spacer(Modifier.height(10.dp))
                IntRangeButton(mt("字体大小"), textStyle.fontSize.value.toInt(), 8, 50) {
                    textStyle = textStyle.copy(fontSize = it.sp, lineHeight = (it*1.5).sp)
                }


                if(vMode == viewModes.listen){
                    Row(
                        modifier = Modifier
                            .alpha(0.8f)
                            .height(50.dp)
                    ) {
                        var buttonTitle by remember { mutableStateOf("AutoSpeak") }
                        Button(onClick = {
                            isOpenSpeaking = !isOpenSpeaking
                            if (buttonTitle == "AutoSpeak") {
                                buttonTitle = "Speaking"
                                speakOut()
                            } else {
                                buttonTitle = "AutoSpeak"
                                tts.stop()
                            }
                        }) {
                            Text(mt(buttonTitle)) // Set text color to soft white
                        }
                        Column(modifier = Modifier.padding(5.dp)) {
                            Text(
                                mt("播放速度") + ": ${
                                    String.format(
                                        "%.1f",
                                        speechRate
                                    )
                                }"
                            ) // Set text color to soft white
                            Slider(
                                value = speechRate,
                                onValueChange = {
                                    speechRate = it
                                    tts.setSpeechRate(speechRate)
                                    if (isInitialized && tts.isSpeaking) {
                                        // Stop speaking the current sentence
                                        tts.stop()
                                        // Reinitialize TTS with the new voice
                                        // Continue speaking from the current index
                                        continueSpeakingFromIndex(currentSentenceIndex)
                                    }
                                },
                                valueRange = 0.1f..5.0f, // Extend the range to 5
                                steps = 50
                            )
                        }
//                        RangeButton("播放频率", speechVolume, 0.5f, 2.0f) {
//                            speechVolume = it
//                            tts.setPitch(speechVolume)
//                        }
                    }
                }
                Row ( horizontalArrangement = Arrangement.spacedBy(10.dp)){
                    Button(onClick = {
                        loadTextFromScan()
                    }) { MText("扫描") }
                    if(vMode == viewModes.read) {
                        Button(onClick = {
                            canMark = true
                            InfoDialog.show {
                                Card {
                                    Column(modifier = Modifier.padding(5.dp)) {
                                        IntRangeButton("Top级别", topValue, 0, 7) {
                                            topValue = it
//                                    UserStatus.defInterface.set("BookTopValue",3)
                                        }
                                        IntRangeButton("历史记录天数", historyValue, 0, 100) {
                                            historyValue = it
//                                    UserStatus.defInterface.set("BookHistoryValue",7)
                                        }
                                    }
                                }
                            }
                        }) { MText("标记") }
                    }
                }
                Divider(
                    modifier = Modifier.padding(vertical = 8.dp),
                    color = Color.LightGray, // 分割线颜色
                    thickness = 1.dp, // 分割线厚度
                )
            }
        }
        //听书页面
        @Composable
        fun ListenBookData.ListenPage() {
            Column {

                LazyColumn(
                    state = getScrollState(),
                    modifier = Modifier
                        .fillMaxSize() // Remove padding
                        .background(bColor)
                        .scrollEnabled(!HomeEvents.downMenuOpen)
                ) {
                    //每一段的输出
                    itemsIndexed(textToRead) {it,name->
                        textColors.add(Color.Unspecified)
                        _Text(
                            index = it,
                            text = name,
                            modifier = Modifier
                                .background(textColors[it])
                                .wrapContentWidth()
                                .padding(10.dp)
                                .clickable {
                                    continueSpeakingFromIndex(j2dMap[it])
                                }
                        )
                    }
                }
            }
        }
        //书本加载页面
        @Composable
        fun ListenBookData.LoadBookPage() {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .clickable {
                        NavScreen.BookmarkScreen.open()
                    },
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                Text(
                    text = stringResource(R.string.Selectdatabase),
                    style = MaterialTheme.typography.titleMedium,
                    color = MaterialTheme.colorScheme.onSurface,
                )
            }
        }
        //读书页面
        @OptIn(ExperimentalLayoutApi::class)
        @Composable
        fun ListenBookData.ReadPage() {
            val words = remember (textToRead){
                derivedStateOf {
                    textToRead.joinToString("\n")
                        .split(Regex("[\\W\\s]+"))
                        .filter { it.matches(Regex("[\\w`]+")) }
                        .toSet().map{it.lowercase()}
                }
            }
            //字体集合
            val fColor = MaterialTheme.colorScheme.onBackground;
            var rtfs = remember(words,historyValue,topValue) { derivedStateOf {
                RichTextFonts(
                    RichTextFont(
                        color = fColor,
                        type = RichTextFonts.Type.top,
                        level = topValue
                    ),
                    RichTextFont(
                        color = fColor,
                        fontWeight = FontWeight.Bold,
                        type = RichTextFonts.Type.history,
                        level = historyValue
                    ),
                    RichTextFont(
                        color = Color.Gray,
                    )
                ).apply {
                    if(words.value.size>0) {
                        setWords(words.value)
                    }
                }
            }}
            var items = textToRead //List(1000){ "创建项$it"}
            Box (modifier = Modifier.fillMaxSize()){
                LazyColumn(
                    state = getScrollState(),
                    modifier = Modifier
                        .background(bColor)
                        .fillMaxSize() // Remove padding
                        .scrollEnabled(!HomeEvents.downMenuOpen)
                ) {

                    //每一段的输出
                    itemsIndexed(items) {i,it->
                        // 判断当前项是否在可见区域内
                        val isVisible = remember( scrollState!!.layoutInfo.visibleItemsInfo) {
                            scrollState!!.layoutInfo.visibleItemsInfo.any { i == it.index  }
                        }
                        RichText(
                            it,
                            isVisible = isVisible && !scrollState!!.isScrollInProgress,
                            defStyle=textStyle,
                            fonts = if (canMark) rtfs.value else null,
                            onWordClick = {
                                GlobalVal.tts.speak(it)
                                DictionaryDatabase.getDatabase(ActivityRun.context).ch(it)
                            },
                            onPopInfoClick = { word ->
                                bgRun {
                                    val wordModel = Db.dictionary.dictionaryDao.find(word)
                                    var pic = ""
                                    if (wordModel != null) {
                                        if (wordModel.hasPic()) {
                                            pic = wordModel.pic
                                        }
                                        MainRun {
                                            InfoDialog.show {
                                                Card(backgroundColor = MaterialTheme.colorScheme.background) {
                                                    LazyColumn {
                                                        item {
                                                            Row {
                                                                Spacer(Modifier.weight(1f))
                                                                CloseButton { InfoDialog.close() }
                                                            }
                                                            DefaultPageWordDetail(
                                                                wordModel,
                                                                pic
                                                            )
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            },
                            searchKey = searchQuery,
                            selected = searchQueryPos.y==i,
                            searchSelectedIndex = searchQueryPos.x
                        ){
                            _Text(
                                index = i,
                                text = it,
                            )
                        }
                    }
                }

            }
        }

        /**
         * 词频统计页
         */
        @Composable
        fun ListenBookData.StatPage() {
            Box {
                if(sortedList.value.size==0){
                    Column {
                        Text(mt("statisticsing")+"...",Modifier.padding(10.dp))
                        LinearProgressIndicator(
                            //0.0表示没有进度，1.0表示已完成进度
                            progress = progress.value,
                            modifier = Modifier
                                .padding(10.dp)
                                .fillMaxWidth(),
                            color = Color.Green,
                        )
                    }
                }else {
                    LazyColumn(
                        state = getScrollState(),
                        modifier = androidx.compose.ui.Modifier
                            .fillMaxSize() // Remove padding

                    ) {
                        var sum = 0f
                        itemsIndexed(sortedList.value) {index,it->
                            Row (modifier = Modifier.clickable {
                                tts.speak(it.first,TextToSpeech.QUEUE_FLUSH, null, UUID.randomUUID().toString())
                            }){
                                if(index==0) sum =0f;
                                sum+=it.second
                                val num = String.format("%.2f%%--%.2f%%(%d)",(it.second.toFloat()/docWordSum*100),(sum/docWordSum*100), it.second);
                                Text((index+1).toString()+".", modifier = Modifier.padding(0.dp,0.dp,5.dp,0.dp))
                                Text(it.first)
                                Spacer(modifier = Modifier.weight(1f))
                                Text(num)
                            }
                        }
                    }
                }
            }
        }
        //源文件页面
        @OptIn(ExperimentalFoundationApi::class)
        @Composable
        fun ListenBookData.SourcePage(){
            Column {
                if(sourceImg!=null) {
                    val bp = BitmapPainter(sourceImg!!.asImageBitmap());
                    Image(
                        bp,
                        null,
                        modifier = Modifier.height(300.dp)
                            .combinedClickable(
                                onClick = {
                                    InfoDialog.show {
                                        Image(
                                            bp,null,
                                            modifier = Modifier.fillMaxSize()
                                        )
                                    }
                                },
                                onLongClick = {
                                    val img = InputImage.fromBitmap(sourceImg!!, 0)
                                    Image2Text.convert(img){ text->
                                        textToRead = text;
                                        val entity:ArticleEntity = article!!.entity
                                        entity.content = text.joinToString("\n");
                                        Article.update(entity);
                                    }
                                }
                            )
                    )
                    val vScsroll = rememberLazyListState();
                    HomeEvents.status.openDrowUp = vScsroll.firstVisibleItemIndex==0
                    HomeEvents.status.enableDrowDown = remember(vScsroll) {
                        derivedStateOf {
                            // 获取列表布局信息
                            val layoutInfo = vScsroll.layoutInfo
                            // 总项数
                            val totalItemsCount = layoutInfo.totalItemsCount
                            if (totalItemsCount == 0) {
                                // 没有数据时视为“已在结尾”
                                return@derivedStateOf true
                            }
                            // 最后一个可见项的索引
                            val lastVisibleItemIndex = layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
                            // 当最后一个可见项索引 >= 总项数 - 1 时，视为到达结尾
                            // 可根据需求调整偏移量（如 -3 表示提前3项判断为接近结尾）
                            lastVisibleItemIndex >= totalItemsCount - 1
                        }
                    }.value
                    LazyColumn(
                        state = vScsroll,
                        modifier = Modifier
                            .background(bColor)
                            .fillMaxSize() // Remove padding
                    ) {
                        //每一段的输出
                        itemsIndexed(textToRead) { i, it ->
                            Text(it);
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun ListenBookData.getScrollState(): LazyListState {
    scrollState = rememberLazyListState()

//            dIndex = scrollState!!.firstVisibleItemIndex
    // 1. 获取第一个可见项的索引（最顶部可见项）
    val firstVisibleIndex = scrollState!!.firstVisibleItemIndex
    // 2. 获取最后一个可见项的索引（最底部可见项）
    val lastVisibleIndex by remember {
        derivedStateOf {
            scrollState!!.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
        }
    }
    // 监听索引变化（示例）
    LaunchedEffect(firstVisibleIndex, lastVisibleIndex) {
        scrollIndex = firstVisibleIndex+1
//                UserStatus.defInterface.set("bookPos", scrollIndex)
        println("当前第一个可见项：$firstVisibleIndex")
        println("当前最后一个可见项：$lastVisibleIndex")
    }
    // 1. 判断是否滚动到头部（顶部）
    val isAtTop by remember {
        derivedStateOf {
            // 第一个可见项的索引为0，且滚动偏移为0 → 完全在顶部
            scrollState!!.firstVisibleItemIndex == 0 &&
                    scrollState!!.firstVisibleItemScrollOffset == 0
        }
    }

    // 2. 判断是否滚动到底部
    val isAtBottom by remember {
        derivedStateOf {
            // 最后一个可见项的索引 >= 总项数 - 1 → 到达底部
            val lastVisibleIndex = scrollState!!.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
            val totalItems = scrollState!!.layoutInfo.totalItemsCount
            lastVisibleIndex >= totalItems - 1
        }
    }
    // 监听滚动状态变化
    LaunchedEffect(isAtTop, isAtBottom,firstVisibleIndex) {
        HomeEvents.status.openDrowUp = isAtTop && scrollIndex==1
        HomeEvents.status.enableDrowDown = isAtBottom
    }
    if(scrollState!!.isScrollInProgress && !(isAtBottom && isAtBottom)){
        if(!showPos) {
            showPos = true
            stringRun(5000) {
                showPos = false
            }
        }
    }

    return scrollState!!
}

@Composable
fun RadioLableButton(lable:String,isCheck:Boolean,onClick:()->Unit){
    Row (modifier = Modifier
        .clickable {
            onClick()
        },
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(0.dp)
    ){
        RadioButton(
            selected = isCheck ,
            onClick = {
                onClick();
            },
            modifier = Modifier.padding(0.dp)
        )
        MText(text = lable)
    }
}

@Composable
fun RangeButton(name:String,
                defaultValue:Float,
                start:Float,
                end:Float,
                steps:Int = 50,
                onChange:(v:Float)->Unit ={}
){
    var speechVolume by remember { mutableStateOf(defaultValue) }
    Row{
        Column (modifier = Modifier.padding(1.dp)){
            Text(
                "$name:"+ String.format(
                    "%.1f",
                    speechVolume
                )
            )
            Slider(
                value = speechVolume,
                onValueChange = {
                    speechVolume = it
                    onChange(it)
                },
                valueRange = start..end, // Extend the range to 5
                steps = steps
            )
        }
    }
}

@Composable
fun IntRangeButton(name:String,
                   defaultValue:Int,
                   start:Int,
                   end:Int,
                   onChange:(v:Int)->Unit ={}
){
    var speechVolume by remember { mutableStateOf(defaultValue) }
    Row{
        Column (modifier = Modifier.padding(1.dp)){
            Text(
                "$name: "+speechVolume
            )
            Slider(
                value = speechVolume.toFloat(),
                onValueChange = {
                    speechVolume = it.toInt()
                    onChange(speechVolume)
                },
                valueRange = start.toFloat()..end.toFloat(), // Extend the range to 5
                steps = end-start
            )
        }
    }
}

@Composable
fun ListenBookData._Text(text:String,modifier: Modifier=Modifier,index:Int=0){
    if(searchQuery.isEmpty()) {
        Text(
            text = text,
            style=textStyle,
            modifier = modifier
        )
    }else{
        val annotatedText = annotatedText(text,searchQuery,searchQueryPos.y==index,searchQueryPos.x)

        Text(
            text = annotatedText,
            style = textStyle,
            modifier = modifier,
            onTextLayout = { layoutResult ->
                if(searchQueryPos.y==index) {
                    // 计算每个目标字符的偏移高度
                    // 1. 找到字符所在的行
                    val lineIndex = layoutResult.getLineForOffset(searchPos)
                    // 2. 获取该行的基线位置（基线到文本顶部的距离即为垂直偏移）
                    searchScrollOffset = layoutResult.getLineBaseline(lineIndex).toInt()
                }
            }
        )
    }
}


